package com.mano233.server.config.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.Set;

/**
 * 动态URL验证
 * @author mano233
 */
@Component("rbacauthorityservice")
public class RbacAuthority {
    private static Logger logger = LoggerFactory.getLogger(RbacAuthority.class);
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        Object userInfo = authentication.getPrincipal();
        boolean hasPermission = false;
        if (userInfo == null) {
            return false;
        }
        if (userInfo instanceof UserCustomDetails) {
            UserCustomDetails details = (UserCustomDetails) userInfo;
            Set<String> urls = new HashSet<>();
            urls.add("/event/**");
            // 其余页面将需要验证
            AntPathMatcher antPathMatcher = new AntPathMatcher();
            for (String url : urls) {
                if (antPathMatcher.match(url, request.getRequestURI())) {
                    hasPermission = true;
                    break;
                }
            }
            logger.info("userInfo:" + details.getUserName());
        }
        logger.warn("authentication is not UserCustomDetails");
        return hasPermission;
    }
}
